/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-03 14:14:47
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.BpIndustrialPipelineBean;
import com.joysuch.wwyt.bp.bean.BpIndustrialPipelineListBean;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpIndustrialPipeline;
import com.joysuch.wwyt.bp.entity.dsl.QBpIndustrialPipeline;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpIndustrialPipelineDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpIndustrialPipelineService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.entity.MhMajorHazardChemProduct;
import com.joysuch.wwyt.mh.repository.MhMajorHazardChemProductDao;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
@Transactional
public class BpIndustrialPipelineServiceImpl implements BpIndustrialPipelineService {

    @Autowired
    private BpIndustrialPipelineDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private MhMajorHazardChemProductDao mhMajorHazardChemProductDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;

    @Override
    public void add(BpIndustrialPipelineBean p) {
        BpIndustrialPipeline i = new BpIndustrialPipeline();
        BeanUtils.copyProperties(p, i);
        if (StringUtils.isEmpty(p.getUniCode())) {
            i.setUniCode(bizCodeGeneratorFacade.gongYeGuanDao());
        } else {
            i.setUniCode(p.getUniCode());
        }
        if (p.getCommissioningDate() != null && !"".equals(p.getCommissioningDate())) {
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = fmt.parse(p.getCommissioningDate());
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
                e.printStackTrace();
            }
            i.setCommissioningDate(date);
        }
        setWorkpressureAndTemperature(p, i);
        if (p.getHchId() != null) {
            MhMajorHazardChemProduct one = mhMajorHazardChemProductDao.getOne(p.getHchId());
            if (one != null) {
                i.setHchName(one.getName());
                i.setCas(one.getCasNo());
            }
        }
        if (StringUtils.isBlank(p.getIsHchPipeline()) || p.getIsHchPipeline().equals("N")) {
            i.setHchName(null);
            i.setCas(null);
            i.setHchId(null);
        }
        if (StringUtils.isBlank(p.getIsPressurePipeline()) || p.getIsPressurePipeline().equals("N")) {
            i.setPressureLevel(null);
        }
        BpIndustrialPipeline save = dao.save(i);
        addOrUpdateDeviceFacilityCollection(save);
        checkCode(save);
    }

    @Override
    public void update(BpIndustrialPipelineBean p) {
        BpIndustrialPipeline i = dao.getOne(p.getId());
        BeanUtils.copyProperties(p, i);
        if (StringUtils.isNotBlank(p.getCommissioningDate())) {
            try {
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                Date date = fmt.parse(p.getCommissioningDate());
                i.setCommissioningDate(date);
            } catch (Exception e) {
            }
        }
        setWorkpressureAndTemperature(p, i);
        if (StringUtils.isEmpty(p.getUniCode())) {
            i.setUniCode(bizCodeGeneratorFacade.gongYeGuanDao());
        } else {
            i.setUniCode(p.getUniCode());
        }
        if (p.getHchId() != null) {
            MhMajorHazardChemProduct one = mhMajorHazardChemProductDao.getOne(p.getHchId());
            i.setHchName(one.getName());
            i.setCas(one.getCasNo());
        }
        if (StringUtils.isBlank(p.getIsHchPipeline()) || p.getIsHchPipeline().equals("N")) {
            i.setHchName(null);
            i.setCas(null);
            i.setHchId(null);
        }
        if (StringUtils.isBlank(p.getIsPressurePipeline()) || p.getIsPressurePipeline().equals("N")) {
            i.setPressureLevel(null);
        }
        BpIndustrialPipeline save = dao.save(i);
        addOrUpdateDeviceFacilityCollection(save);
        checkCode(save);
    }

    private void addOrUpdateDeviceFacilityCollection(BpIndustrialPipeline save) {
        // 保存到集中统一的表中
        BpDeviceFacilityCollection device = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(
                DeviceFacilityTypes.GONG_YE_GUAN_DAO, save.getId(), save.getCode(), save.getName(), null,
                null, null);

    }

    private void checkCode(BpIndustrialPipeline save) {
        int count = dao.countByCode(save.getCode());
        if (count > 1) {
            throw new IllegalArgumentException("工业管道编码已存在");
        }
    }

    /**
     * @param p
     * @param i
     */
    protected void setWorkpressureAndTemperature(BpIndustrialPipelineBean p, BpIndustrialPipeline i) {
        if (p.getWorkPressureHighRange() != null) {
            String[] split1 = p.getWorkPressureHighRange();
            if (StringUtils.isNotBlank(split1[0])) {
                i.setWorkPressureLowValue(Float.parseFloat(split1[0]));
            }
            if (StringUtils.isNotBlank(split1[1])) {
                i.setWorkPressureHighValue(Float.parseFloat(split1[1]));
            }
        }
        if (p.getWorkTemperatureRange() != null) {
            String[] split = p.getWorkTemperatureRange();
            if (StringUtils.isNotBlank(split[0])) {
                i.setWorkTemperatureLowValue(Float.parseFloat(split[0]));
            }
            if (StringUtils.isNotBlank(split[1])) {
                i.setWorkTemperatureHighValue(Float.parseFloat(split[1]));
            }

        }
    }

    @Override
    public Page<BpIndustrialPipelineListBean> findByPage(Pageable page, String name, Integer currentState) {
        QBpIndustrialPipeline bpIndustrialPipeline = QBpIndustrialPipeline.bpIndustrialPipeline;
        Predicate predicate = bpIndustrialPipeline.isNotNull();
        predicate = name == null ? predicate
                : ExpressionUtils.and(predicate, ExpressionUtils.or(bpIndustrialPipeline.name.like("%" + name + "%"),
                bpIndustrialPipeline.code.like("%" + name + "%")));
        predicate = currentState == null ? predicate
                : ExpressionUtils.and(predicate, bpIndustrialPipeline.currentState.eq(currentState));

        Page<BpIndustrialPipeline> data = dao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data, bpIndustrialPipeline1 -> {
            BpIndustrialPipelineListBean tempBean = new BpIndustrialPipelineListBean();
            tempBean.setId(bpIndustrialPipeline1.getId());
            tempBean.setCode(bpIndustrialPipeline1.getCode());
            tempBean.setName(bpIndustrialPipeline1.getName());
            tempBean.setTransportMedium(bpIndustrialPipeline1.getTransportMedium());
            tempBean.setCurrentState(bpIndustrialPipeline1.getCurrentState());
            Integer state = bpIndustrialPipeline1.getCurrentState();
            tempBean.setCurrentStateName(getPiplelineCurrentStateName(state));
            tempBean.setIsPressurePipeline(bpIndustrialPipeline1.getIsPressurePipeline());
            tempBean.setResponsibleDept(bpIndustrialPipeline1.getResponsibleDept());
            String deptName = bpDepartDao.getNameById(Long.valueOf(bpIndustrialPipeline1.getResponsibleDept()));
            tempBean.setResponsibleDeptName(deptName);
            return tempBean;
        });
    }

    public static String getPiplelineCurrentStateName(Integer state) {
        return (state == null || state.intValue() == 0) ? "运行" : state.intValue() == 1 ? "停产" : "检修";
    }

    @Override
    public void delete(Long id) {
        /*
         * QBpIndustrialPipeline bpIndustrialPipeline = QBpIndustrialPipeline.bpIndustrialPipeline;
         * Predicate predicate = bpIndustrialPipeline.isNotNull();
         * predicate = id == null ? predicate : ExpressionUtils.and(predicate, bpIndustrialPipeline.id.eq(id));
         * Iterable<BpIndustrialPipeline> all = dao.findAll(predicate);
         * for (BpIndustrialPipeline industrialPipeline : all) {
         * dao.delete(industrialPipeline);
         * }
         */
        dao.deleteById(id);
        bpDeviceFacilityCollectionService.delteByDeviceTypeAndDeviceId(DeviceFacilityTypes.GONG_YE_GUAN_DAO, id);
    }

    @Override
    public BpIndustrialPipeline findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public BpIndustrialPipelineBean getById(Long id) {
        BpIndustrialPipeline p = dao.findById(id).get();
        BpIndustrialPipelineBean i = new BpIndustrialPipelineBean();

        // i.setActualOpTemperature(p.getActualOpTemperature());
        // i.setActualOpPressure(p.getActualOpPressure());
        i.setId(p.getId());
        i.setCas(p.getCas());
        i.setCode(p.getCode());
        if (p.getCommissioningDate() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(p.getCommissioningDate());
            i.setCommissioningDate(format);
        }
        i.setCurrentState(p.getCurrentState());
        i.setCurrentStateName(parseStateName(p.getCurrentState()));
        i.setDesignPressure(p.getDesignPressure());
        i.setIsPressurePipeline(p.getIsPressurePipeline());
        i.setIsPressurePipelineName(BizUtils.translateYesNoToChinese(p.getIsPressurePipeline()));
        i.setIsHchPipeline(p.getIsHchPipeline());
        i.setIsHchPipelineName(BizUtils.translateYesNoToChinese(p.getIsHchPipeline()));
        i.setLength(p.getLength());
        i.setMaterial(p.getMaterial());
        i.setMediumState(p.getMediumState());//
        i.setName(p.getName());
        Float workPressureHighValue = p.getWorkPressureHighValue();
        Float workPressureLowValue = p.getWorkPressureLowValue();
        Float workTemperatureHighValue = p.getWorkTemperatureHighValue();
        Float workTemperatureLowValue = p.getWorkTemperatureLowValue();
        if (workPressureLowValue != null && workPressureHighValue != null) {
            i.setWorkPressureHighRange(new String[]{workPressureLowValue + "", workPressureHighValue + ""});
        }
        if (workTemperatureLowValue != null && workTemperatureHighValue != null) {
            i.setWorkTemperatureRange(new String[]{workTemperatureLowValue + "", workTemperatureHighValue + ""});
        }
        i.setOpTemperatureHighValue(p.getOpTemperatureHighValue());
        i.setOpTemperatureLowValue(p.getOpTemperatureLowValue());
        i.setOpPressureLowValue(p.getOpPressureLowValue());
        i.setOpPressureHighValue(p.getOpPressureHighValue());
        i.setPressureLevel(convertPressureLevel(p.getPressureLevel()));
        i.setSetupMethod(p.getSetupMethod());
        i.setTransportAbility(p.getTransportAbility());
        i.setTransportMedium(p.getTransportMedium());
        i.setUniCode(p.getUniCode());
        i.setHchId(p.getHchId());
        i.setResponsibleDept(p.getResponsibleDept());
        String deptName = bpDepartDao.getNameById(Long.valueOf(p.getResponsibleDept()));
        i.setResponsibleDeptName(deptName);
        if (p.getHchId() != null) {
            MhMajorHazardChemProduct one = mhMajorHazardChemProductDao.getOne(p.getHchId());
            i.setHchName(one.getName());
        }

        return i;
    }

    private String parseStateName(Integer currentState) {
        if (currentState == null) {
            return null;
        } else if (currentState == 0) {
            return "运行";
        } else if (currentState == 1) {
            return "停产";
        } else if (currentState == 2) {
            return "检修";
        }
        return null;
    }

    private String convertPressureLevel(String pressureLevel) {
        if ("1".equals(pressureLevel)) {
            return "低压";
        } else if ("2".equals(pressureLevel)) {
            return "中压";
        } else if ("3".equals(pressureLevel)) {
            return "高压";
        } else if ("4".equals(pressureLevel)) {
            return "超高压";
        }
        return pressureLevel;
    }

}
